﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ServerLibrary.Concrete
{
    class SSI
    {
        public SSI(string Text)
        {
            Thread = Text;
        }
        public string Thread
        {
            set { thread = value; }
            get { return thread; }
        }
        public string HtmlThread
        {
            set { htmlThread = value; }
            get { return htmlThread; }
        }
        public void ChangeThread()
        {
            string paterrn = "(?<=<!--#include file=\").*(?=\"-->)";
            string paterrn2 = "(<!--#include file).*?(-->)";
            MatchCollection matches = Regex.Matches(Thread, paterrn2);
            string[] filenames = new string[matches.Count];

            for (int i = 0; i < matches.Count; i++)
            {
                filenames[i] = Regex.Matches(matches[i].ToString(), paterrn)[0].ToString();
            }

            for (int i = 0; i < matches.Count; i++)
            {
                Regex rgx = new Regex(paterrn2);
                Thread = rgx.Replace(Thread, ReadFile(filenames[i]), 1);
            }
        }
        public string ReadFile(string filename)
        {
            try
            {
                System.IO.StreamReader file = new System.IO.StreamReader(filename);
                HtmlThread = file.ReadToEnd();
            }
            catch (System.IO.FileNotFoundException ex)
            {
                throw new System.IO.FileNotFoundException("Unable to open file", ex);
            }
            catch (Exception ex)
            {
                throw new Exception("Exception", ex);
            }
            return HtmlThread;
        }
        private string thread = "";
        private string htmlThread = "";
    }
}